import Server from "./server";

const koa = require('koa2')
const app =  new koa()
const properties = require('properties')

const propertiesConfig = {
    namespaces: true, sections: true, variables: true, include: true, path: true,
    comments: ['#', ';', '!'], separators: ['=', ':'], strict: true, vars: true,
    reviver: function (key: string, value?: any, section?: string) {
        //Do not split section lines
        if (this.isSection) return this.assert();

        //Split all the string values by a comma
        if (typeof value === "string") {
            const values = value.split(",").map(item => item.trim());
            return values.length === 1 ? value : values;
        }

        //Do not split the rest of the lines
        return this.assert();
    }
}

export default class FlaxApp{

    /**
     * 启动应用程序服务器
     * @param cls 启动类
     * @param args 启动参数
     */
    public static run(cls?:FlaxApp, ...args:string[]):void{
        // 扫描所有配置文件信息
        properties.parse('test/application.properties', propertiesConfig, (err, data)=>{
            for (const section of Object.getOwnPropertyNames(data)) {
                const configObj = data[section]

                if(global[section] === undefined){
                    continue
                }
                if(global[section]._ConfigurationProperties==section){      // 检测为配置属性类
                    for (const config of Object.getOwnPropertyNames(global[section])) {
                        if(configObj[config] != null) global[section][config] = configObj[config]       //赋值
                    }
                }
            }
            console.log("配置文件application.properties加载完毕！")
            app.use((ctx)=>{
                ctx.body = 'hello world!'
            })
            // 启动服务器
            app.listen(Server.port,  (err, res)=>{
                console.log('服务器已启动，访问地址', `${Server.protocol}://${Server.host}:${Server.port}`)
            })
        })
    }
}

/**
 * 服务器启动类装饰器
 * @constructor
 * @param target
 */
export function FlaxApplication(target):void{

}